import 'package:craze/common/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:craze/stores/index.dart';
import 'package:get_it/get_it.dart';
import 'dart:io';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class CreateTeamView extends StatefulWidget {
  const CreateTeamView({super.key});

  @override
  State<CreateTeamView> createState() => _CreateTeamViewState();
}

class _CreateTeamViewState extends State<CreateTeamView> {
  final TeamStore _teamStore = GetIt.instance<TeamStore>();
  final ChatStore _chatStore = GetIt.instance<ChatStore>();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _descController = TextEditingController();
  final TextEditingController _titleController = TextEditingController();
  int? _selectedMax;
  DateTime? _selectedDate;
  String? _coverImage;
  bool _isCreating = false;
  AssetEntity? _selectedAsset;
  File? _selectedImageFile;

  @override
  void dispose() {
    _nameController.dispose();
    _descController.dispose();
    _titleController.dispose();
    super.dispose();
  }

  Future<void> _pickDate() async {
    final now = DateTime.now();
    final picked = await showDatePicker(
      context: context,
      initialDate: now,
      firstDate: now,
      lastDate: now.add(const Duration(days: 365)),
    );
    if (picked != null) {
      setState(() {
        _selectedDate = picked;
      });
    }
  }

  Future<void> _pickCover() async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.image,
        themeColor: Colors.blue,
      ),
    );
    if (result != null && result.isNotEmpty) {
      final File? file = await result.first.file;
      if (file != null) {
        setState(() {
          _selectedAsset = result.first;
          _selectedImageFile = file;
          _coverImage = null; // 清除默认图片
        });
      }
    }
  }

  Future<void> _handleCreate() async {
    if (_isCreating) return;
    final title = _titleController.text.trim();
    final desc = _descController.text.trim();
    final date = _selectedDate;
    final max = _selectedMax;
    if (title.isEmpty) {
      MyToast.showError(context, 'Please enter team name');
      return;
    }
    if (max == null) {
      MyToast.showError(context, 'Please select team number (2-6)');
      return;
    }
    if (max < 2 || max > 6) {
      MyToast.showError(context, 'Team number must be between 2 and 6');
      return;
    }
    if (date == null) {
      MyToast.showError(context, 'Please select departure date');
      return;
    }
    if (desc.isEmpty) {
      MyToast.showError(context, 'Please enter team introduction');
      return;
    }
    setState(() => _isCreating = true);
    final team = await _teamStore.createTeam(
      name: title,
      departureDate: date,
      maxMembers: max,
      description: desc,
      backgroundImage:
          _selectedImageFile != null
              ? _selectedImageFile!.path
              : MyImages.teamBg,
    );
    setState(() => _isCreating = false);
    if (team != null) {
      await _teamStore.loadTeams();
      // 创建群聊
      final authStore = GetIt.instance<AuthStore>();
      final creatorId = authStore.currentUser?.id;
      final participants = List<String>.from(team.memberIds);
      if (creatorId != null && !participants.contains(creatorId)) {
        participants.add(creatorId);
      }
      await GetIt.instance<ChatStore>().createGroupChat(
        participantIds: participants,
        groupName: team.name,
        groupAvatar: team.backgroundImage,
      );
      if (mounted) {
        Navigator.of(context).pop(true);
        MyToast.showSuccess(context, 'Team created successfully');
      }
    } else {
      MyToast.showError(context, 'Failed to create team, please try again');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: 1.sw,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 顶部操作
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        GoRouter.of(context).pop();
                      },
                      child: Icon(
                        MyIcons.iconBack,
                        color: Colors.white,
                        size: 24.sp,
                      ),
                    ),
                    Expanded(
                      child: Center(
                        child: Text(
                          'create',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 22.sp,
                            fontWeight: FontWeight.w400,
                            fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 17.h),
                // 创建日期
                Text(
                  'Creation Date',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(height: 13.h),
                GestureDetector(
                  onTap: _pickDate,
                  child: Container(
                    height: 52.h,
                    alignment: Alignment.centerLeft,
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment(0.50, 0.00),
                        end: Alignment(0.50, 0.86),
                        colors: [
                          Color(0xFF0076FF).withAlpha(60),
                          Color(0xFF045EC6).withAlpha(60),
                        ],
                      ),
                      borderRadius: BorderRadius.circular(10.r),
                      border: Border.all(color: MyColors.blue, width: 1.w),
                    ),
                    child: Text(
                      _selectedDate == null
                          ? 'Please select departure date'
                          : '${_selectedDate!.year}-${_selectedDate!.month}-${_selectedDate!.day}',
                      style: TextStyle(
                        color: Colors.white.withAlpha(180),
                        fontSize: 16.sp,
                      ),
                    ),
                  ),
                ),
                SizedBox(height: 16.h),
                // 人数选择
                Text(
                  'Number of people',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(height: 13.h),
                Container(
                  height: 52.h,
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment(0.50, 0.00),
                      end: Alignment(0.50, 0.86),
                      colors: [
                        Color(0xFF0076FF).withAlpha(60),
                        Color(0xFF045EC6).withAlpha(60),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(10.r),
                    border: Border.all(color: MyColors.blue, width: 1.w),
                  ),
                  child: DropdownButtonHideUnderline(
                    child: Theme(
                      data: Theme.of(context).copyWith(
                        canvasColor: MyColors.cardDark,
                        dialogBackgroundColor: MyColors.cardDark,
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        focusColor: Colors.transparent,
                        hoverColor: Colors.transparent,
                      ),
                      child: DropdownButton<int>(
                        value: _selectedMax,
                        hint: Text(
                          'Please select team number (2-6)',
                          style: TextStyle(
                            color: Colors.white.withAlpha(180),
                            fontSize: 16.sp,
                          ),
                        ),
                        dropdownColor: MyColors.cardDark,
                        style: TextStyle(color: Colors.white, fontSize: 16.sp),
                        icon: SizedBox.shrink(),
                        borderRadius: BorderRadius.circular(10.r),
                        items:
                            List.generate(5, (i) => i + 2)
                                .map(
                                  (v) => DropdownMenuItem<int>(
                                    value: v,
                                    child: Container(
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(
                                          10.r,
                                        ),
                                      ),
                                      padding: EdgeInsets.symmetric(
                                        vertical: 6.h,
                                        horizontal: 8.w,
                                      ),
                                      child: Text(
                                        '$v',
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 16.sp,
                                        ),
                                      ),
                                    ),
                                  ),
                                )
                                .toList(),
                        onChanged: (v) {
                          setState(() {
                            _selectedMax = v;
                          });
                        },
                        isExpanded: true,
                      ),
                    ),
                  ),
                ),
                SizedBox(height: 16.h),
                // 介绍
                Text(
                  'Introduction',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(height: 13.h),
                Container(
                  height: 52.h,
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment(0.50, 0.00),
                      end: Alignment(0.50, 0.86),
                      colors: [
                        Color(0xFF0076FF).withAlpha(60),
                        Color(0xFF045EC6).withAlpha(60),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(10.r),
                    border: Border.all(color: MyColors.blue, width: 1.w),
                  ),
                  child: TextField(
                    controller: _descController,
                    style: TextStyle(color: Colors.white, fontSize: 16.sp),
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: 'Please enter team introduction',
                      hintStyle: TextStyle(color: Colors.white.withAlpha(180)),
                    ),
                  ),
                ),
                SizedBox(height: 24.h),
                // 新增团队名输入框
                Text(
                  'Team Title',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(height: 13.h),
                Container(
                  height: 52.h,
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment(0.50, 0.00),
                      end: Alignment(0.50, 0.86),
                      colors: [
                        Color(0xFF0076FF).withAlpha(60),
                        Color(0xFF045EC6).withAlpha(60),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(10.r),
                    border: Border.all(color: MyColors.blue, width: 1.w),
                  ),
                  child: TextField(
                    controller: _titleController,
                    style: TextStyle(color: Colors.white, fontSize: 16.sp),
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: 'Please enter team name',
                      hintStyle: TextStyle(color: Colors.white.withAlpha(180)),
                    ),
                  ),
                ),
                SizedBox(height: 16.h),
                // 封面选择
                Text(
                  'Cover Image',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(height: 13.h),
                GestureDetector(
                  onTap: _pickCover,
                  child: Container(
                    width: 130.w,
                    height: 157.h,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment(0.50, 0.00),
                        end: Alignment(0.50, 0.86),
                        colors: [
                          Color(0xFF0076FF).withAlpha(60),
                          Color(0xFF045EC6).withAlpha(60),
                        ],
                      ),
                      borderRadius: BorderRadius.circular(10.r),
                      border: Border.all(color: MyColors.blue, width: 1.w),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(10.r),
                      child:
                          _selectedAsset != null && _selectedImageFile != null
                              ? Image.file(
                                _selectedImageFile!,
                                fit: BoxFit.cover,
                              )
                              : _coverImage != null
                              ? Image.asset(_coverImage!, fit: BoxFit.cover)
                              : Center(
                                child: Icon(
                                  MyIcons.iconAdd,
                                  color: Colors.white,
                                  size: 24.sp,
                                ),
                              ),
                    ),
                  ),
                ),
                SizedBox(height: 24.h),
                // 创建按钮
                GestureDetector(
                  onTap: _handleCreate,
                  child: Container(
                    height: 52.h,
                    width: double.infinity,
                    decoration: ShapeDecoration(
                      gradient: LinearGradient(
                        begin: Alignment(0.50, 0.00),
                        end: Alignment(0.50, 0.86),
                        colors: [Color(0xFF0076FF), Color(0xFF045EC6)],
                      ),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30.r),
                      ),
                    ),
                    child: Center(
                      child:
                          _isCreating
                              ? SizedBox(
                                width: 24.w,
                                height: 24.w,
                                child: CircularProgressIndicator(
                                  color: Colors.white,
                                  strokeWidth: 2,
                                ),
                              )
                              : Text(
                                'Create',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18.sp,
                                  fontFamily:
                                      GoogleFonts.mochiyPopOne().fontFamily,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                    ),
                  ),
                ),
                const Spacer(),
                // Eula
                GestureDetector(
                  onTap: () {
                    WangYe.openUrl(
                      'https://www.freeprivacypolicy.com/live/d6a9a407-9d63-42af-9bc0-471389957c78',
                    );
                  },
                  child: Align(
                    alignment: Alignment.center,
                    child: Text(
                      'EULA',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.sp,
                        fontFamily: GoogleFonts.inter().fontFamily,
                        fontWeight: FontWeight.w400,
                        decoration: TextDecoration.underline,
                      ),
                    ),
                  ),
                ),
                const Spacer(),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
